<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import ChannelSelect from './channelSelect.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { articleAddService, articleGetInfo, articleUpdateInfo } from '@/api/article'
import { baseURL } from '@/utils/request'
import axios from 'axios'

// 定义抽屉开关
const visible = ref(false)
// 定义img
const imgUrl = ref('')
// open方法
const open = async (row) => {
  visible.value = true
  modelform.value = {
    title: '',
    cate_id: '',
    content: '',
    cate_name: '',
    cover_img: '',
    state: '',
  }
  if (row.id) {
    // 根据每行的id获取文章信息
    const res = await articleGetInfo(row.id)
    // 将获取到的信息 赋值给modelform进行回显
    modelform.value = res.data.data
    // 将图片地址和服务器地址进行拼接
    imgUrl.value = baseURL + modelform.value.cover_img
    const file = await urlToFile(imgUrl.value)
    modelform.value.cover_img = file
    console.log('编辑操作')
  } else {
    console.log('添加操作')
    modelform.value = { ...row }
  }
  console.log(row)
}

// 数据对象
const modelform = ref({
  title: '',
  cate_id: '',
  content: '',
  cate_name: '',
  cover_img: '',
  state: '',
})

// 定义formRef标识
const formRef = ref()

// 定义emit
const emit = defineEmits(['success', 'edit'])
// 定义规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { pattern: /^\S{2,10}$/, message: '文章标题长度必须在2到10个非空字符之间', trigger: 'blur' },
  ],
  cate_id: [{ required: true, message: '请输入选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
}

// 定义图片上传方法
const handlechange = (img) => {
  // 将图片转换格式并赋值给imgUrl
  imgUrl.value = URL.createObjectURL(img.raw)
  // 将图片数据赋值给modelform
  modelform.value.cover_img = img.raw
}

// 添加发布方法
const onPubulish = async (key) => {
  modelform.value.state = key
  // 每次调用onPubulish时，重新创建formData对象
  const formData = new FormData()

  for (let key in modelform.value) {
    formData.append(key, modelform.value[key])
  }

  // 发送请求
  if (!modelform.value.id) {
    await articleAddService(formData)
    ElMessage.success('添加成功')
    emit('success')
  } else {
    await articleUpdateInfo(formData)
    ElMessage.success('修改成功')
    emit('edit')
  }

  // 成功提示
  ElMessage.success('发布成功')
  // 通知父组件刷新页面
  emit('success')
  // 关闭抽屉
  visible.value = false
}

// 将图片转换成file对象
async function urlToFile(imageUrl) {
  try {
    // 1. 使用 axios 获取图片的 Blob 数据
    const response = await axios.get(imageUrl, {
      responseType: 'blob', // 关键：声明响应类型为二进制数据
    })

    // 2. 从响应头或 URL 中提取文件名
    let fileName = 'image.jpg' // 默认文件名
    const contentDisposition = response.headers['content-disposition']

    // 优先从 Content-Disposition 中解析文件名
    if (contentDisposition) {
      const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i
      const matches = fileNameRegex.exec(contentDisposition)
      if (matches && matches[1]) {
        fileName = matches[1].replace(/['"]/g, '')
      }
    } else {
      // 如果响应头中没有，从 URL 路径截取文件名
      const urlParts = imageUrl.split('/')
      fileName = urlParts[urlParts.length - 1]
    }

    // 3. 将 Blob 转换为 File 对象
    const blob = response.data
    const file = new File([blob], fileName, {
      type: blob.type || 'application/octet-stream', // 确保 MIME 类型正确
    })

    return file
  } catch (error) {
    console.error('转换失败:', error)
    throw error // 抛出错误供外部处理
  }
}

// 暴露方法
defineExpose({
  open,
})
</script>

<template>
  <el-drawer
    v-model="visible"
    :title="modelform.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    :size="'60%'"
  >
    <el-form :model="modelform" :rules="rules" ref="formRef">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="modelform.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <ChannelSelect v-model="modelform.cate_id"></ChannelSelect>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="handlechange"
          :auto-upload="false"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor theme="snow" v-model:content="modelform.content" contentType="html">
          </quill-editor>
        </div>
      </el-form-item>
    </el-form>

    <el-button type="primary" label="发布" @click="onPubulish('已发布')">发布</el-button>
    <el-button label="草稿" @click="onPubulish('草稿')">草稿</el-button>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
